package com.zhugang.week13.linkedlist;

/**
 * @program algorithms
 * @description: middleNode
 * @author: chanzhugang
 * @create: 2022/10/22 23:15
 */
public class MiddleNode {

    /**
     * 876 链表的中间节点
     * https://leetcode.cn/problems/middle-of-the-linked-list/
     *
     * @param head
     * @return
     */
    public ListNode middleNode(ListNode head) {
        // 快慢指针
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        // fast == null || fast.next == null
        return slow;
    }

    public ListNode middleNode2(ListNode head) {
        // 单指针法：先遍历一次，记录节点个数n，在遍历n/2
        ListNode p = head;
        int k1 = 0;
        while (p != null) {
            k1++;
            p = p.next;
        }

        int k2 = 0;
        p = head;
        while (k2 < k1 / 2) {
            k2++;
            p = p.next;
        }
        return p;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}